# -*- coding: utf-8 -*-
import json
import os
import requests
import time
import logging
from openai import OpenAI

logger = logging.getLogger()


def request_tryon_model(top_garment_url, person_image_url, bottom_garment_url=''):
    url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis/"

    payload = json.dumps({
        "model": "aitryon",
        "input": {
            "top_garment_url": top_garment_url,
            "bottom_garment_url": bottom_garment_url,
            "person_image_url": person_image_url
        },
        "parameters": {
            "resolution": -1,
            "restore_face": True
        }
    })
    headers = {
        'X-DashScope-Async': 'enable',
        'Authorization': f'Bearer ' + os.environ.get('DASHSCOPE_API_KEY'),
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    return handle_response(response)


def request_tryon_refiner(top_garment_url, person_image_url, coarse_image_url, gender, bottom_garment_url=''):
    url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis/"

    payload = json.dumps({
        "model": "aitryon-refiner",
        "input": {
            "top_garment_url": top_garment_url,
            "person_image_url": person_image_url,
            "bottom_garment_url": bottom_garment_url,
            "coarse_image_url": coarse_image_url
        },
        "parameters": {
            "gender": gender
        }
    })
    headers = {
        'X-DashScope-Async': 'enable',
        'Authorization': f'Bearer ' + os.getenv("DASHSCOPE_API_KEY"),
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    return handle_response(response)


def handle_response(response):
    error_data = response.json()
    error_code = error_data.get("code")
    error_message = error_data.get("message")
    if response.status_code != 200:
        if error_code == "InvalidParameter":
            return False, "入参格式不对"
        elif error_code == "InvalidURL":
            return False, "输入图片下载失败，请检查网络或者输入格式"
        elif error_code == "InvalidPerson":
            return False, "输入图片中没有人或多人主体"
        elif error_code == "InvalidInputLength":
            return False, "上传图片大小不符合要求"
        elif error_code == "InvalidParameter.DataInspection":
            return False, "在数据检查过程中无法下载媒体资源"
        elif error_code == "InvalidFile.Content":
            return False, "输入图片中人体不完整或者没有人体"
        elif error_code == "InvalidFile.Resolution":
            return False, "上传图片大小不符合要求"
        elif error_code == "InternalError.Algo":
            return False, "算法运行错误"
        elif error_code == "InvalidApiKey" or error_code == "invalid_api_key":
            return False, "百炼 API-KEY错误"
        elif error_code == "AccessDenied.Unpurchased":
            return False, "尚未未开通百炼服务，请前往模型广场开通模型服务"
        elif error_code == "Arrearage":
            return False, "当前账号已欠费，请充值后，等待10分钟后重试"
        else:
            return False, error_message
    else :
        data = response.json()
        status = data["output"]["task_status"]
        if status == "PENDING" or status == "PRE-PROCESSING" or status == "RUNNING":
            task_id = data["output"]["task_id"]
            result = get_result(task_id)
            return True, result


def request_shoe_model(template_image_url, shoe_image_url):
    """ 调用试鞋相模型 """
    url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/virtualmodel/generation"
    payload = json.dumps({
        "model": "shoemodel-v1",
        "input": {
            "template_image_url": template_image_url,
            "shoe_image_url": [
                shoe_image_url
            ]
        },
        "parameters": {
            "n": 4
        }
    })
    headers = {
        'X-DashScope-Async': 'enable',
        'Authorization': f'Bearer ' + os.getenv("DASHSCOPE_API_KEY"),
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    return handle_response(response)


def get_result(task_id):
    """ 获取模型处理结果 """
    if task_id is None:
        return
    url = 'https://dashscope.aliyuncs.com/api/v1/tasks/' + task_id
    headers = {
        'Authorization': f'Bearer ' + os.getenv("DASHSCOPE_API_KEY"),
    }
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            data = response.json()
            task_status = data["output"]["task_status"]
            if task_status == "PENDING" or task_status == "RUNNING":
                time.sleep(1)
                logger.info("task_id: " + task_id + " 异步处理中...")
                return get_result(task_id)

            if data["output"]["task_status"] == "FAILED":
                logger.error(data["output"]["message"])
                return None
            image_url = data['output'].get('image_url')
            if image_url is None:
                results = data["output"]["results"]
                return [item['url'] for item in results if item['url']]
            else:
                return data['output']['image_url']
        else:
            logger.error(response.text)
            return None
    except Exception as error:
        logger.error(error)
        return None


def get_gender(image_url):
    """获取人物性别"""
    client = OpenAI(
        # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
        api_key=os.getenv('DASHSCOPE_API_KEY'),
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    completion = client.chat.completions.create(
        model="qwen-vl-max-latest",  # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
        messages=[
            {'role': 'system', 'content': '你是人物性别鉴定专家。'},
            {
                'role': 'user',
                'content': [
                    {
                        'type': 'image_url',
                        'image_url': {
                            'url': image_url
                        }
                    },
                    {
                        'type': 'text',
                        'text': "提取人物的性别直接返回 man/woman"
                    }
                ]
            }
        ])
    return completion.choices[0].message.content
